package com.shankungfu.main;

import java.io.File;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.alibaba.fastjson.JSON;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.shankungfu.GlobleConstant;
import com.shankungfu.MainApplication;
import com.shankungfu.R;
import com.shankungfu.adapter.PickItemDetailAdapter;
import com.shankungfu.bean.BaseBean;
import com.shankungfu.bean.InterestInBean;
import com.shankungfu.bean.PickItemDetailBean;
import com.shankungfu.bean.ProjectDetailDataBean;
import com.shankungfu.util.MyAsyncHttpResponseHandler;
import com.shankungfu.util.PhoneUtils;
import com.shankungfu.util.ToastUtil;
import com.shankungfu.util.WebService;
import com.shankungfu.view.HorizontalListView;

public class PickItemDetailActivity extends Activity implements
		OnClickListener, OnItemClickListener {

	public static final int SUCCESS_CODE = 100;
	public static final String SHARE_CONTENT = "SHARE_CONTENT";
	public static final String SHARE_TITLE = "SHARE_TITLE";
	public static final String SHARE_FILE_PATH = "SHARE_FILE_PATH";
	private static final int DATE_SUCCESS = 1;
	private static final int FAVORITE_DATA_SUCCESS = 2;
	private static final int FAVORITE = 3;
	private static final int JOIN = 4;
	private static final int COMMENT = 5;

	public static String PROJECT_ID = "PROJECT_ID";

	private HorizontalListView listView;

	private String projectId = "0";
	private PickItemDetailAdapter adapter;

	private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	private ImageLoader imageLoader;

	private TextView title;
	private TextView date;
	private TextView address;
	private TextView volunteer_time;
	private TextView area;
	private TextView recruit;
	private TextView navigation_title;
	private RelativeLayout progressBar;
	private ImageView image_pic;
	private Button need_time;
	private Button need_skill;
	private Button fit_crowd;
	private TextView pro_pic_number;
	private TextView pro_introduce;
	private Button favorite_pepole;
	private Button join_pepole;
	private Button comment_pepole;
	private String[] imageUrls;
	private Context context;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch (msg.what) {
			case DATE_SUCCESS:
				PickItemDetailBean detailBean = (PickItemDetailBean) msg.obj;
				adapter.setData(detailBean.getProjectImgData());
				adapter.notifyDataSetChanged();
				break;
			case FAVORITE_DATA_SUCCESS:
				InterestInBean interestInBean = (InterestInBean) msg.obj;
				if (interestInBean.getMsg().length() != 0) {
					ToastUtil.showMessageText(context, interestInBean.getMsg());
					favorite_pepole.setText("感兴趣\n(" + interestInBean.getInterest_count() + "人)");
				}
				break;
			}
		}
	};
	
	private ImageGetter imgGetter = new Html.ImageGetter() {
		
		@Override
		public Drawable getDrawable(String source) {
			Drawable drawable = new BitmapDrawable();
//			drawable = getResources().getDrawable(R.drawable.default_icon);
			 
			
			
//			
//			Bitmap bitmap = imageLoader.loadImageSync(source);
//			drawable = new BitmapDrawable(bitmap);
//	        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable  
//	                          .getIntrinsicHeight());  
	        return drawable;   
		}  
	};  
	
	private ProjectDetailDataBean dataBean;
	private ImageView rightButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pickitem_detail_layout);

		context = PickItemDetailActivity.this;

		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			projectId = bundle.getString(PROJECT_ID);
		}
		initView();
		initData();
		updateForData();
		getData();
	}

	private void initData() {

		imageLoader = ImageLoader.getInstance();
		adapter = new PickItemDetailAdapter(this, MainApplication.getOptions());
		listView.setAdapter(adapter);
	}

	private void initView() {
		listView = (HorizontalListView) findViewById(R.id.pic_listview);
		
		navigation_title = (TextView) findViewById(R.id.detail_title);

		title = (TextView) findViewById(R.id.detail_title_textview);
		date = (TextView) findViewById(R.id.detail_date);
		address = (TextView) findViewById(R.id.detail_address);
		volunteer_time = (TextView) findViewById(R.id.detail_volunteer_time);
		area = (TextView) findViewById(R.id.detail_skill);
		recruit = (TextView) findViewById(R.id.detail_recruit);
		progressBar = (RelativeLayout) findViewById(R.id.progressBar);
		rightButton = (ImageView) findViewById(R.id.head_refresh);

		image_pic = (ImageView) findViewById(R.id.image_pic);

		need_time = (Button) findViewById(R.id.need_time);
		need_skill = (Button) findViewById(R.id.need_skill);
		fit_crowd = (Button) findViewById(R.id.fit_crowd);

		pro_pic_number = (TextView) findViewById(R.id.pro_pic_number);
		pro_introduce = (TextView) findViewById(R.id.pro_introduce);

		favorite_pepole = (Button) findViewById(R.id.pickitem_favorite_pepole);
		join_pepole = (Button) findViewById(R.id.pickitem_join_pepole);
		comment_pepole = (Button) findViewById(R.id.pickitem_comment_pepole);

		rightButton.setImageResource(R.drawable.share_image);
		pro_introduce.setMovementMethod(LinkMovementMethod.getInstance());
		
		listView.setOnItemClickListener(this);
		image_pic.setOnClickListener(this);
		favorite_pepole.setOnClickListener(this);
		join_pepole.setOnClickListener(this);
		comment_pepole.setOnClickListener(this);
		
		navigation_title.setText("项目详情");
	}

	private void getData() {
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", "project_detail");
		params.add("project_Id", projectId);

		AsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				getSuccessData();
				if (!TextUtils.isEmpty(content)
						&& content.contains("\"result\":0")) {
					PickItemDetailBean detailBean = JSON.parseObject(content,
							PickItemDetailBean.class);

					setDataForView(detailBean);

					imageUrls = detailBean.getProjectImgData().toArray(
							new String[] {});

					Message msg = new Message();
					msg.what = DATE_SUCCESS;
					msg.obj = detailBean;
					handler.sendMessage(msg);

				}
			}

			@Override
			public void onFailure(String content) {
			}
		};
		httpclient.request(GlobleConstant.PICKITEM_DETAIL_ADD, params,
				responseHandler);
	}

	private void setDataForView(PickItemDetailBean detailBean) {
		dataBean = detailBean.getProjectDetailData();

		title.setText(dataBean.getProject_title());
		String startTime = PhoneUtils.TimeStamp2DateForSKF(dataBean
				.getProject_time().getStart_time());
		String endTime = PhoneUtils.TimeStamp2DateForSKF(dataBean
				.getProject_time().getEnd_time());
		date.setText("日期：" + startTime + " ~ " + endTime);
		address.setText("地点：" + dataBean.getProject_address());
		volunteer_time.setText("所需志愿时：" + dataBean.getProject_services_time()
				+ "小时");
		area.setText("领域：" + dataBean.getProject_area());
		recruit.setText("招募者：" + dataBean.getProject_leader());

		imageLoader
				.displayImage(dataBean.getProject_img_url()
						.getActivity_avatar(), image_pic, MainApplication.getOptions(),
						animateFirstListener);

		need_time.setText("所需志愿时\n" + dataBean.getProject_services_time()
				+ "小时");
		need_skill.setText("所需技能\n" + dataBean.getProject_skill());
		fit_crowd.setText("适合群体\n" + dataBean.getProject_group());

		pro_pic_number.setText("项目图片(" + detailBean.getProjectImgData().size()
				+ ")");
		pro_introduce.setText(Html.fromHtml(dataBean.getIntroduction(), imgGetter, null));

		favorite_pepole.setText("感兴趣\n(" + dataBean.getPeople_number() + "人)");
		join_pepole.setText("要参加\n(" + dataBean.getJoin_number() + "人)");
		comment_pepole.setText("评论\n(" + dataBean.getComment_number() + "人)");
	}

	private static class AnimateFirstDisplayListener extends
			SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections
				.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view,
				Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}

	private void startImagePagerActivity(int position) {
		Intent intent = new Intent(this, ImagePagerActivity.class);
		intent.putExtra(com.shankungfu.GlobleConstant.Extra.IMAGES, imageUrls);
		intent.putExtra(com.shankungfu.GlobleConstant.Extra.IMAGE_POSITION,
				position);
		startActivity(intent);
	}

	private void updateForData() {
		progressBar.setVisibility(View.VISIBLE);
	}

	private void getSuccessData() {
		progressBar.setVisibility(View.GONE);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.head_goback:
			finish();
			break;
		case R.id.head_refresh:
			showShare();
			break;
		case R.id.image_pic:

			if (dataBean != null
					&& !TextUtils.isEmpty(dataBean.getProject_img_url()
							.getActivity_avatar())) {
				imageUrls = new String[] { dataBean.getProject_img_url()
						.getActivity_avatar() };
				startImagePagerActivity(0);
			}
			break;

		case R.id.pickitem_favorite_pepole:
			userInteraction(FAVORITE);
			break;
		case R.id.pickitem_join_pepole:
			userInteraction(JOIN);
			break;
		case R.id.pickitem_comment_pepole:
			userInteraction(COMMENT);
			break;
		}

	}

	// private void shareWeibo() {
	// Intent intent = new Intent(context, WeiboMoreActivity.class);
	// File f = imageLoader.getDiscCache().get(dataBean.getProject_img_url()
	// .getActivity_avatar());
	//
	// intent.putExtra(SHARE_FILE_PATH, f.getAbsolutePath());
	// intent.putExtra(SHARE_TITLE, dataBean.getProject_title());
	// intent.putExtra(SHARE_CONTENT, "欢迎使用我们的客户端，请多多支持与关注！谢谢。");
	// startActivity(intent);
	// }

	private void showShare() {
		ShareSDK.initSDK(context);

		if (dataBean == null) return;
		
		File file = imageLoader.getDiscCache().get(
				dataBean.getProject_img_url().getActivity_avatar());

		final OnekeyShare oks = new OnekeyShare();
		oks.setNotification(R.drawable.ic_launcher,
				context.getString(R.string.app_name));
		oks.setAddress("741227905@qq.com");
		oks.setTitle(dataBean.getProject_title());
		oks.setTitleUrl("http://shankungfu.org/");
		oks.setText(dataBean.getProject_title()
				+ " | 1000个劝募小伙伴 - 善功夫 一个基于兴趣、技能的义工招募平台 （分享自 @善功夫）");
		oks.setImagePath(file.getAbsolutePath());
		oks.setImageUrl(file.getAbsolutePath());
		oks.setUrl("http://shankungfu.org/");
		oks.setFilePath(file.getAbsolutePath());
		oks.setComment(context.getString(R.string.share));
		oks.setSite(context.getString(R.string.app_name));
		oks.setSiteUrl("http://shankungfu.org/");
		oks.setVenueName("ShanKungFu");
		oks.setVenueDescription("ShanKungFu");
		oks.setSilent(false);
		// if (platform != null) {
		// oks.setPlatform(platform);
		// }

		// 去除注释，可令编辑页面显示为Dialog模式
		// oks.setDialogMode();

		// 去除注释，在自动授权时可以禁用SSO方式
		// oks.disableSSOWhenAuthorize();

		// 去除注释，则快捷分享的操作结果将通过OneKeyShareCallback回调
		// oks.setCallback(new OneKeyShareCallback());
		oks.setShareContentCustomizeCallback(new cn.sharesdk.onekeyshare.ShareContentCustomizeDemo());

		oks.show(context);
	}

	private void shareWeibo1() {
		ShareSDK.initSDK(context);

		OnekeyShare oks = new OnekeyShare();

		// 分享时Notification的图标和文字
		oks.setNotification(R.drawable.ic_launcher,
				context.getString(R.string.app_name));
		// address是接收人地址，仅在信息和邮件使用
		oks.setAddress("12345678901");
		// title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
		oks.setTitle(context.getString(R.string.share));
		// titleUrl是标题的网络链接，仅在人人网和QQ空间使用
		oks.setTitleUrl("http://sharesdk.cn");
		// text是分享文本，所有平台都需要这个字段
		oks.setText("要分享的内容");
		// imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
		// oks.setImagePath(MainActivity.TEST_IMAGE);
		// imageUrl是图片的网络路径，新浪微博、人人网、QQ空间、
		// 微信的两个平台、Linked-In支持此字段
		oks.setImageUrl("http://img.appgo.cn/imgs/sharesdk/content/2013/07/25/1374723172663.jpg");
		// url仅在微信（包括好友和朋友圈）中使用
		oks.setUrl("http://sharesdk.cn");
		// appPath是待分享应用程序的本地路劲，仅在微信中使用
		// oks.setAppPath(MainActivity.TEST_IMAGE);
		// comment是我对这条分享的评论，仅在人人网和QQ空间使用
		// oks.setComment(getContext().getString(R.string.share));
		// site是分享此内容的网站名称，仅在QQ空间使用
		oks.setSite(context.getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用
		oks.setSiteUrl("http://sharesdk.cn");
		// venueName是分享社区名称，仅在Foursquare使用
		oks.setVenueName("Southeast in China");
		// venueDescription是分享社区描述，仅在Foursquare使用
		oks.setVenueDescription("This is a beautiful place!");
		// latitude是维度数据，仅在新浪微博、腾讯微博和Foursquare使用
		oks.setLatitude(23.122619f);
		// longitude是经度数据，仅在新浪微博、腾讯微博和Foursquare使用
		oks.setLongitude(113.372338f);
		// 是否直接分享（true则直接分享）
		oks.setSilent(true);
		// 指定分享平台，和slient一起使用可以直接分享到指定的平台
		// if (platform != null) {
		// oks.setPlatform(platform);
		// }
		// 去除注释可通过OneKeyShareCallback来捕获快捷分享的处理结果
		// oks.setCallback(new OneKeyShareCallback());
		// 通过OneKeyShareCallback来修改不同平台分享的内容
		// oks.setShareContentCustomizeCallback(
		// new ShareContentCustomizeDemo());

		oks.show(context);

	}

	private void userInteraction(int categroy) {

		if (MainApplication.isUserIsLogin()) { // 将我要感兴趣的Id，发过去

			switch (categroy) {
			case FAVORITE: // 点击了感兴趣
				getMyFavoriteData();
				break;
			case JOIN: // 点击了 参加
				Intent aIntent = new Intent(context, ApplyActivity.class);
				aIntent.putExtra("project_id", projectId);
				context.startActivity(aIntent);
				break;
			case COMMENT: // 点击了 参加
				startCommentActivity();
				break;
			}
			return;

		} else { // 如果没有登录，就跳到登录页面，登录
			if (categroy != COMMENT) {
				ToastUtil.showMessageText(context, "请先登录");
				Intent intent = new Intent(context, LogInActivity.class);
				startActivityForResult(intent, SUCCESS_CODE);
			} else {
				startCommentActivity();
			}
		}
	}

	private void startCommentActivity() {
		Intent cIntent = new Intent(context, CommentActivity.class);
		cIntent.putExtra("project_id", projectId);
		startActivity(cIntent);

	}

	private void getMyFavoriteData() {
		WebService httpclient = new WebService();
		RequestParams params = new RequestParams();
		params.add("serviceId", "project_interest");
		params.add("app_info", "shankungfu");
		params.add("user_id", MainApplication.userBean.getLoginData()
				.getUser_Id());
		params.add("project_Id", projectId);
		params.add("user_name", MainApplication.userBean.getLoginData().getUser_name());
		AsyncHttpResponseHandler responseHandler = new MyAsyncHttpResponseHandler() {
			@Override
			public void onSuccess(String content) {
				getSuccessData();
				if (!TextUtils.isEmpty(content)) {
					InterestInBean interestInBean = JSON.parseObject(content,
							InterestInBean.class);

					Message msg = new Message();
					msg.what = FAVORITE_DATA_SUCCESS;
					msg.obj = interestInBean;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onFailure(String content) {
			}
		};
		httpclient.request(GlobleConstant.ACTIVITY_INSTEREST_IN, params,
				responseHandler);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == SUCCESS_CODE) {
			startCommentActivity();
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		startImagePagerActivity(position);
	}

}
